package com.adcc.ags.gms.core.interceptor;

import com.adcc.ags.gms.core.entity.SysUser;
import com.adcc.ags.gms.core.service.CoreService;
import com.google.common.base.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private CoreService coreService;

    /**
     * Handler执行完成之后调用这个方法
     */
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception exc)
            throws Exception {

    }

    /**
     * Handler执行之后，ModelAndView返回之前调用这个方法
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * Handler执行之前调用这个方法
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //获取Session
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute("user");
        if (session.getAttribute("user") != null) {
            //判断角色权限 如果为admin 不进行拦截

            if ("admin".equals(user.getName())) {
                return true;
            } else {
                //  值班用户进行拦截
                if (request.getRequestURI().contains("/GMS/turn")) {
                    //  获取请求的URL的参数
                    String param = request.getQueryString();
                    //  如果角色匹配则跳转，否则跳转到登录界面
                    Optional option = coreService.isExistMenuItem(user.getType(), param);
                    if (option.isPresent()) {
                        if ((int) option.get() > 0) {
                            return true;
                        }
                    }
                    return false;
                }
                return true;
            }
        } else {
            //不符合条件的，或路径错误的；跳转到登录界面
            request.getRequestDispatcher("//").forward(request, response);
//            response.sendRedirect("/GMS/");
            return false;
        }

    }
}